package com.weactivity.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weactivity.dto.Result;
import com.weactivity.entity.Activity;
import com.weactivity.service.ActivityService;
import com.weactivity.utils.QRCodeGenerator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.Resource;
import java.util.Base64;

@RestController
@RequestMapping("/api/share")
public class ActivityShareController {

    @Resource
    private ActivityService activityService;

    @GetMapping("/generateQRForSharing")
    public ResponseEntity<String> generateQRForSharing(@RequestParam("id") Integer activityId)
    {
        try{

            Activity one = activityService.findActivityById(activityId);

            //将活动信息JSON序列化
            ObjectMapper mapper = new ObjectMapper();
            String shareContent;
            try {
                shareContent = new String(mapper.writeValueAsString(one));
            } catch (JsonProcessingException e) {
                throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "JsonProcessingException");
            }
            // 生成二维码图片字节数组
            byte[] qrCodeBytes = QRCodeGenerator.generateAsByteArray(shareContent, 300, 300);
            // 将字节数组转换为Base64字符串以便于前端显示
            String base64QRCode = Base64.getEncoder().encodeToString(qrCodeBytes);
            return ResponseEntity.ok(base64QRCode);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to generate QR Code.");
        }
        }

}

